package com.zoweunion.mechanic.controller.base;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.zoweunion.mechanic.entity.CarTemplateBean;
import com.zoweunion.mechanic.entity.PartsTemplateBean;
import com.zoweunion.mechanic.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSONObject;
import com.zoweunion.mechanic.controller.BaseController;
import com.zoweunion.mechanic.model.ResponseBean;
import com.zoweunion.mechanic.model.User;
import com.zoweunion.mechanic.service.base.PartsService;
import com.zoweunion.mechanic.util.constants.Constants;
import com.zoweunion.mechanic.util.MyException;
import org.springframework.web.multipart.MultipartFile;

/**
 * 配件控制层
 * @author Administrator
 */
@RestController
@RequestMapping("/parts")
@SuppressWarnings("unchecked")
public class PartsController extends BaseController{
	
	@Autowired
	private PartsService partsService;


	/**
	 * 获取名称，类型，规格
	 * @throws MyException
	 */
	@PostMapping("/getDictionaries")
	public ResponseBean getDictionariesList(HttpServletRequest request) throws MyException{
		logBefore(logger, "获取名称，类型，规格");
		Map<String, Object> reqMap = new HashMap<>();
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		Map<String, Object> resultMap=partsService.getDictionariesList(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}

	/**
	 * 获取配件列表(分页,条件模糊,排序)
	 * @throws MyException 
	 */
	@PostMapping("/list")
	public ResponseBean list(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "配件管理_列表展示");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		Map<String, Object> resultMap=partsService.getPageQuery(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",resultMap);
	}
	
	/**
	 * 配件新增
	 */
	@PostMapping("/add")
	public ResponseBean add(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "配件管理_新增");
		Map<String,Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		reqMap.put("s_id",currentUser.getS_id());
		//插入前需要根据dictionaries_code校验是否已经存在
		int exist = partsService.checkExistByDictionaries_code(reqMap);
		if(exist>0) {
			return new ResponseBean(Constants.CODE_HANDEL_FAILED,"已存在该编号的配件",reqMap);
		}
		reqMap.put("update_user",currentUser.getId());
		reqMap.put("create_user",currentUser.getId());
		try {
			partsService.insert(reqMap);
		} catch (Exception e) {
			
			return new ResponseBean(Constants.CODE_ACCESS_PROHIBITED,"操作失败,配件参数不全",null);
		}
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
	}
	
	
	/**
	 * 配件编辑
	 */
	@PostMapping("/edit")
	public ResponseBean edit(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "配件管理_编辑");
		Map<String,Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		reqMap.put("s_id",currentUser.getS_id());
		reqMap.put("update_user",currentUser.getId());
		partsService.update(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
	}
	
	
	/**
	 * 配件删除
	 */
	@PostMapping("/delete")
	public ResponseBean delete(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "配件管理_编辑");
		Map<String,Object> reqMap = JSONObject.parseObject(str, Map.class);
		User currentUser = getCurrentUser(request);
		reqMap.put("delete_flag", 1);
		reqMap.put("s_id",currentUser.getS_id());
		reqMap.put("update_user",currentUser.getId());
		partsService.update(reqMap);
		logAfter(logger);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",null);
	}


	/**
	 *
	 * @throws MyException
	 */
	@PostMapping("/getParameterList")
		public ResponseBean getParameterList(@RequestBody String str,HttpServletRequest request) throws MyException{
		logBefore(logger, "配件管理_列表搜索提示");
		Map<String, Object> reqMap = JSONObject.parseObject(str, Map.class);
		reqMap.put("s_id", getCurrentUser(request).getS_id());
		List<String> parameterList=partsService.getParameterList(reqMap);
		return new ResponseBean(Constants.CODE_SUCCESS,"操作成功",parameterList);
	}

	/**
	 *
	 * 配件管理-导入功能
	 *
	 * @param multipartFile
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/uploadParts")
	public ResponseBean uploadParts(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws Exception {
		User currentUser = getCurrentUser(request);
		ImportParams params = new ImportParams();
		List<PartsTemplateBean> result = ExcelImportUtil.importExcel(multipartFile.getInputStream(), PartsTemplateBean.class, params);
		partsService.uploadParts(result,currentUser);
		return new ResponseBean(Constants.CODE_SUCCESS, "操作成功", "");
	}

	/**
	 * 下载模板
	 */

	@GetMapping("downTemplate")
	public void downTemplate(HttpServletResponse response) {
		InputStream inputStream = null;
		ServletOutputStream servletOutputStream = null;
		try {
			Resource resource = new DefaultResourceLoader().getResource("classpath:uploadFileTemplate/partsTemplate.xlsx");
			response.setContentType("application/force-download");
			response.setHeader("Content-Disposition", "attachment;fileName=" + new String("批量上传配件模板".getBytes(), StandardCharsets.ISO_8859_1) + ".xlsx");
			inputStream = resource.getInputStream();
			servletOutputStream = response.getOutputStream();
			IOUtils.copy(inputStream, servletOutputStream);
			response.flushBuffer();
		} catch (Exception e) {
		} finally {
			try {
				if (servletOutputStream != null) {
					servletOutputStream.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (Exception e) {
			}
		}
	}
}
